package MicroSpring.common;

import MicroSpring.annotation.Component;
import MicroSpring.annotation.Scope;
import MicroSpring.annotation.aop.Aspect;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class AnntationUtils {

    public static boolean isAnnotationOfComponent(Class clazz){
        if (clazz.getAnnotations().length==0)
            return false;
        if (clazz.isAnnotationPresent(Component.class))
            return true;
        for (Annotation annotation : clazz.getAnnotations()) {
            if (annotation.annotationType().isAnnotationPresent(Component.class)){
                return true;
            }
        }
        return false;
    }

    public static boolean isPrototype(Class clazz){
        if (clazz.getAnnotations().length==0)
            return false;
        if (clazz.isAnnotationPresent(Scope.class)){
            Scope scope = (Scope) clazz.getAnnotation(Scope.class);
            if (scope!=null && scope.value().equals(ScopeEnum.PROTOTYPE.value())){
                return true;
            }
        }
        return false;
    }

    public static boolean isAnnotationOfAspect(Class clazz) {
        if (clazz.isAnnotationPresent(Aspect.class) ){
            return true;
        }
        return false;
    }

    public static Annotation[] getAnnotationByType(Class clazz) {
        return clazz.getAnnotations();
    }

    public static Map<Annotation,Method> getMethodAnnotationByType(Class clazz) {
        Map<Annotation,Method> mp=new HashMap<>();
        for (Method declaredMethod : clazz.getDeclaredMethods()) {
            Annotation[] as = declaredMethod.getDeclaredAnnotations();
            if (as.length>0){
                for (Annotation a : as) {
                    mp.put(a,declaredMethod);
                }
            }
        }
        return mp;
    }
}
